package org.light.framework.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XmlUtil {

	/**
	 * request中的inputStream转Map
	 * 
	 * @param request
	 * @return
	 */
	public static Map<String, String> toMap(HttpServletRequest request) {

		Map<String, String> map = new LinkedHashMap<String, String>();
		try {

			InputStream inputStream  = request.getInputStream();
			return toMap(inputStream, "UTF-8");

		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 将xml文件转Map
	 * @param xmlfile
	 * @return
	 */
	public static Map<String, String> toMap(File xmlfile) {

		Map<String, String> map = new LinkedHashMap<String, String>();
		try {

			InputStream inputStream = new FileInputStream(xmlfile);
			return toMap(inputStream, "UTF-8");

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 字符串转Map
	 * 
	 * @param request
	 * @return
	 */
	public static Map<String, String> toMap(String xmlStr) {
		InputStream inputStream = new ByteArrayInputStream(xmlStr.getBytes());
		return toMap(inputStream, "UTF-8");
	}

	public static Map<String, String> toMap(InputStream inputStream, String charset) {

		Map<String, String> map = new LinkedHashMap<String, String>();
		try {

			SAXReader reader = new SAXReader();
			Document doc = reader.read(inputStream, charset);
			Element root = doc.getRootElement();

			@SuppressWarnings("rawtypes")
			List list = root.elements();

			@SuppressWarnings("rawtypes")
			Iterator it = list.iterator();

			while (it.hasNext()) {

				Element e = (Element) it.next();
				map.put(e.getName(), e.getText());
			}

		} catch (Exception e) {
			System.out.println("xml to map失败，" + e);
		}
		return map;
	}

	/**
	 * Map转Xml字符串
	 * 
	 * @param map
	 * @return
	 */
	public static String toXml(Map<String, String> map) {
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>");
		Set<String> set = map.keySet();
		for (Iterator<String> it = set.iterator(); it.hasNext();) {
			String key = (String) it.next();
			Object value = map.get(key);
			if (value == null) {
				value = "";
			} else {
				sb.append("<" + key + ">" + value + "</" + key + ">");
			}
		}
		sb.append("</xml>");
		try {
			return sb.toString();
		} catch (Exception e) {
		}
		return null;
	}

	public static void main(String[] args) {

		String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><xml><appid><![CDATA[wx805acee4fa45a1a9]]></appid><transaction_id><![CDATA[4006112001201610065940005952]]></transaction_id></xml>";
		System.out.println(toMap(xml));
	}
}
